<template>
  <div class="publish-container">
    <!-- 顶部状态栏 -->
    <div class="status-bar">
      <span class="status-text">12:00</span>
      <div class="status-icons">
        <span class="icon">📶</span>
        <span class="icon">🔋</span>
      </div>
    </div>

    <!-- 导航栏 -->
    <div class="publish-nav">
      <button class="back-btn" @click="handleBack">←</button>
      <h2 class="nav-title">发布笔记</h2>
      <div></div>
    </div>

    <!-- 图片上传区域 -->
    <div class="upload-section">
      <div class="upload-grid">
        <div 
          v-for="(img, index) in images" 
          :key="index" 
          class="upload-item"
        >
          <img v-if="img.preview" :src="img.preview" alt="预览">
          <div class="remove-btn" @click="removeImage(index)">×</div>
        </div>
        <div 
          v-if="images.length < 9" 
          class="upload-item add-btn" 
          @click="triggerFileInput"
        >
          <span class="plus-icon">+</span>
        </div>
      </div>
      <input 
        ref="fileInput" 
        type="file" 
        accept="image/*" 
        multiple 
        style="display: none" 
        @change="handleFileSelect"
      />
    </div>

    <!-- 标题输入 -->
    <div class="input-section">
      <input 
        v-model="formData.title" 
        type="text" 
        class="title-input" 
        placeholder="填写标题会有更多人浏览哦~"
      />
    </div>

    <!-- 内容输入 -->
    <div class="input-section">
      <textarea 
        v-model="formData.content" 
        class="content-input" 
        placeholder="分享你的玩乐发现,玩了什么、体验如何~"
        rows="8"
      ></textarea>
    </div>

    <!-- 话题和@用户 -->
    <div class="tag-section">
      <button class="tag-btn" @click="showTopicModal = true">
        #话题
      </button>
      <button class="tag-btn" @click="showUserModal = true">
        @用户
      </button>
    </div>

    <!-- 添加地点 -->
    <div class="location-section">
      <div class="location-btn" @click="showLocationModal = true">
        <span class="location-icon">📍</span>
        <span class="location-text">{{ formData.location || '添加地点' }}</span>
      </div>
    </div>

    <!-- 话题选择弹窗 -->
    <div v-if="showTopicModal" class="modal" @click.self="showTopicModal = false">
      <div class="modal-content">
        <h3>选择话题</h3>
        <div class="tag-list">
          <div 
            v-for="tag in topics" 
            :key="tag" 
            class="tag-option"
            :class="{ active: formData.topics.includes(tag) }"
            @click="toggleTopic(tag)"
          >
            #{{ tag }}
          </div>
        </div>
        <button class="modal-confirm" @click="showTopicModal = false">确定</button>
      </div>
    </div>

    <!-- 用户选择弹窗 -->
    <div v-if="showUserModal" class="modal" @click.self="showUserModal = false">
      <div class="modal-content">
        <h3>@用户</h3>
        <input 
          v-model="mentionSearch" 
          type="text" 
          placeholder="搜索用户名"
          class="search-input"
        />
        <div class="user-list">
          <div 
            v-for="user in filteredUsers" 
            :key="user.id" 
            class="user-item"
            @click="selectUser(user)"
          >
            <span class="user-avatar">👤</span>
            <span class="user-name">{{ user.nickname }}</span>
          </div>
        </div>
        <button class="modal-confirm" @click="showUserModal = false">确定</button>
      </div>
    </div>

    <!-- 地点选择弹窗 -->
    <div v-if="showLocationModal" class="modal" @click.self="showLocationModal = false">
      <div class="modal-content location-modal">
        <div class="modal-header">
          <h3>添加地点</h3>
          <button class="close-btn" @click="closeLocationModal">×</button>
        </div>
        <div class="location-search">
          <input 
            v-model="locationSearchKeyword" 
            type="text" 
            placeholder="搜索地点、地址"
            class="location-search-input"
            @input="searchLocation"
            @focus="onLocationSearchFocus"
          />
          <span class="search-icon">🔍</span>
          <button 
            class="location-btn" 
            @click="getCurrentLocation"
            :disabled="isLocating"
            title="定位到当前位置"
          >
            {{ isLocating ? '定位中...' : '📍' }}
          </button>
        </div>
        <!-- 地图容器 -->
        <div ref="mapContainer" class="map-container" v-show="showLocationModal"></div>
        <div v-if="locationSearching" class="loading">搜索中...</div>
        <div v-else-if="locationSearchResults.length > 0" class="location-results">
          <div class="result-title">搜索结果</div>
          <div 
            v-for="(location, index) in locationSearchResults" 
            :key="index" 
            class="location-result-item"
            :class="{ active: selectedLocationIndex === index }"
            @click="selectLocationFromList(location, index)"
          >
            <span class="loc-icon">📍</span>
            <div class="location-info">
              <div class="location-name">{{ location.name }}</div>
              <div class="location-address">{{ location.address || location.district }}</div>
            </div>
          </div>
        </div>
        <div v-else-if="locationSearchKeyword && !locationSearching" class="no-results">
          未找到相关地点
        </div>
        <div v-else class="location-tips">
          <div class="tip-title">热门地点</div>
          <div class="location-options">
            <div 
              v-for="loc in defaultLocations" 
              :key="loc.name" 
              class="location-option"
              @click="selectLocation(loc)"
            >
              <span class="loc-icon">📍</span>
              <span>{{ loc.name }}</span>
            </div>
          </div>
        </div>
        <button v-if="formData.location" class="clear-location-btn" @click="clearLocation">
          清除地点
        </button>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-actions">
      <div class="draft-btn" @click="saveDraft">
        <span class="draft-icon">📮</span>
        <span class="draft-text">存草稿箱</span>
      </div>
      <button 
        class="publish-btn" 
        :disabled="!canPublish"
        @click="handlePublish"
      >
        发布笔记
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import axios from '@/api'

const router = useRouter()
const fileInput = ref(null)

const images = ref([])
const formData = ref({
  title: '',
  content: '',
  topics: [],
  mentions: [],
  location: '',
  locationData: null // 存储完整的地点信息
})

const showTopicModal = ref(false)
const showUserModal = ref(false)
const showLocationModal = ref(false)
const mentionSearch = ref('')

// 地点搜索相关
const locationSearchKeyword = ref('')
const locationSearchResults = ref([])
const locationSearching = ref(false)
const selectedLocationIndex = ref(-1)
const mapContainer = ref(null)
const currentLocation = ref(null) // 当前位置信息
const isLocating = ref(false) // 是否正在定位
let placeSearch = null
let searchTimeout = null
let map = null
let markers = []
let currentMarker = null
let geolocation = null // 定位插件

// 话题列表
const topics = ref(['美食', '旅行', '摄影', '萌宠', '美妆', '健身', '手工', '探店'])

// 用户列表（示例）
const users = ref([
  { id: 1, nickname: '用户1' },
  { id: 2, nickname: '用户2' },
  { id: 3, nickname: '用户3' }
])

// 默认热门地点
const defaultLocations = ref([
  { name: '杭州西湖', address: '浙江省杭州市西湖区', location: '120.135,30.259' },
  { name: '上海外滩', address: '上海市黄浦区', location: '121.490,31.240' },
  { name: '北京天安门', address: '北京市东城区', location: '116.397,39.909' },
  { name: '广州塔', address: '广东省广州市海珠区', location: '113.324,23.106' },
  { name: '成都宽窄巷子', address: '四川省成都市青羊区', location: '104.055,30.666' }
])

const filteredUsers = computed(() => {
  if (!mentionSearch.value) return users.value
  return users.value.filter(u => u.nickname.includes(mentionSearch.value))
})

const canPublish = computed(() => {
  return formData.value.title.trim() || formData.value.content.trim()
})

const triggerFileInput = () => {
  fileInput.value?.click()
}

const handleFileSelect = (event) => {
  const files = event.target.files
  if (!files) return

  for (let file of files) {
    if (images.value.length >= 9) break
    
    const reader = new FileReader()
    reader.onload = (e) => {
      images.value.push({
        file: file,
        preview: e.target.result
      })
    }
    reader.readAsDataURL(file)
  }
}

const removeImage = (index) => {
  images.value.splice(index, 1)
}

const toggleTopic = (topic) => {
  const index = formData.value.topics.indexOf(topic)
  if (index > -1) {
    formData.value.topics.splice(index, 1)
  } else {
    formData.value.topics.push(topic)
  }
}

const selectUser = (user) => {
  if (!formData.value.mentions.find(m => m.id === user.id)) {
    formData.value.mentions.push(user)
  }
  showUserModal.value = false
}

// 初始化高德地图地点搜索
const initPlaceSearch = () => {
  if (typeof AMap === 'undefined') {
    console.warn('高德地图SDK未加载')
    return
  }
  
  // PlaceSearch需要通过插件方式加载
  AMap.plugin('AMap.PlaceSearch', () => {
    try {
      placeSearch = new AMap.PlaceSearch({
        pageSize: 10,
        pageIndex: 1,
        city: '', // 全国搜索
        citylimit: false,
        map: map // 关联地图，搜索结果会自动在地图上标记
      })
      console.log('地点搜索初始化成功')
    } catch (error) {
      console.error('初始化高德地图搜索失败:', error)
    }
  })
}

// 初始化地图
const initMap = () => {
  if (typeof AMap === 'undefined') {
    console.warn('高德地图SDK未加载')
    return
  }
  
  if (!mapContainer.value) {
    console.warn('地图容器不存在')
    return
  }
  
  // 检查容器是否有尺寸
  const container = mapContainer.value
  if (container.offsetWidth === 0 || container.offsetHeight === 0) {
    console.warn('地图容器尺寸为0，等待容器渲染')
    setTimeout(() => {
      if (mapContainer.value && !map) {
        initMap()
      }
    }, 200)
    return
  }
  
  try {
    // 创建地图实例
    map = new AMap.Map(mapContainer.value, {
      zoom: 13, // 初始缩放级别
      center: [116.397428, 39.90923], // 初始中心点（北京天安门，如果定位失败则使用此默认位置）
      viewMode: '3D', // 3D视图
      mapStyle: 'amap://styles/normal' // 地图样式
    })
    
    // 地图加载完成后刷新
    map.on('complete', () => {
      console.log('地图加载完成')
      if (map) {
        // 强制刷新地图大小和显示
        setTimeout(() => {
          if (map) {
            map.getSize()
            // 隐藏加载提示
            const container = mapContainer.value
            if (container) {
              container.style.background = 'transparent'
            }
          }
        }, 100)
      }
    })
    
    // 初始化定位插件
    initGeolocation()
    
    // 地图点击事件：允许用户在地图上点击选择地点
    map.on('click', (e) => {
      const lng = e.lnglat.getLng()
      const lat = e.lnglat.getLat()
      
      // 使用逆地理编码获取点击位置的地址信息
      const geocoder = new AMap.Geocoder()
      geocoder.getAddress([lng, lat], (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          const addressComponent = result.regeocode.addressComponent
          const formattedAddress = result.regeocode.formattedAddress
          
          const location = {
            name: addressComponent.township || addressComponent.district || '未知地点',
            address: formattedAddress,
            district: `${addressComponent.district}${addressComponent.adname}`,
            location: `${lng},${lat}`,
            lng: lng,
            lat: lat,
            pname: addressComponent.province,
            cityname: addressComponent.city,
            adname: addressComponent.district
          }
          
          // 在地图上添加标记
          addMarkerToMap([lng, lat], location.name)
          
          // 选择地点
          selectLocation(location)
        }
      })
    })
    
    // 初始化地点搜索（异步加载插件）
    initPlaceSearch()
    
    // 自动获取当前位置（延迟一下，确保地图完全加载）
    setTimeout(() => {
      console.log('开始自动定位...')
      getCurrentLocation()
    }, 800)
    
    console.log('地图初始化成功')
  } catch (error) {
    console.error('初始化地图失败:', error)
  }
}

// 初始化定位插件
const initGeolocation = () => {
  if (typeof AMap === 'undefined' || !map) {
    return
  }
  
  try {
    // 加载定位插件
    AMap.plugin('AMap.Geolocation', () => {
      geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, // 是否使用高精度定位
        timeout: 10000, // 超时时间
        maximumAge: 0, // 定位结果缓存时间
        convert: true, // 自动偏移坐标
        showButton: false, // 不显示定位按钮
        buttonPosition: 'RB', // 定位按钮位置
        showMarker: false, // 不显示定位标记
        showCircle: false, // 不显示定位精度圆圈
        panToLocation: false, // 定位成功后不自动移动地图
        zoomToAccuracy: false // 定位成功后不自动调整缩放级别
      })
      
      // 将定位插件添加到地图
      map.addControl(geolocation)
    })
  } catch (error) {
    console.error('初始化定位插件失败:', error)
  }
}

// 获取当前位置
const getCurrentLocation = () => {
  if (!map) {
    console.warn('地图未初始化，无法定位')
    return
  }
  
  isLocating.value = true
  console.log('开始获取当前位置...')
  
  // 使用浏览器原生定位API（更快速）
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const lng = position.coords.longitude
        const lat = position.coords.latitude
        
        console.log('获取到GPS坐标:', lng, lat)
        
        // 立即定位地图到当前位置（不等待逆地理编码）
        try {
          if (!map) {
            console.warn('地图尚未初始化，等待地图初始化...')
            // 等待地图初始化
            const checkMap = setInterval(() => {
              if (map) {
                clearInterval(checkMap)
                map.setCenter([lng, lat])
                map.setZoom(15)
                addMarkerToMap([lng, lat], '当前位置')
                console.log('✅ 地图已定位到当前位置')
              }
            }, 100)
            // 最多等待5秒
            setTimeout(() => {
              clearInterval(checkMap)
              if (!map) {
                console.error('地图初始化超时')
              }
            }, 5000)
            return
          }
          
          console.log('正在定位地图到坐标:', lng, lat)
          map.setCenter([lng, lat])
          map.setZoom(15)
          
          // 立即添加当前位置标记
          addMarkerToMap([lng, lat], '当前位置')
          
          console.log('✅ 地图已定位到当前位置')
        } catch (error) {
          console.error('定位地图失败:', error)
        }
        
        // 异步获取地址信息（不影响地图定位）
        const geocoder = new AMap.Geocoder()
        geocoder.getAddress([lng, lat], (status, result) => {
          isLocating.value = false
          
          if (status === 'complete' && result.info === 'OK') {
            const addressComponent = result.regeocode.addressComponent
            const formattedAddress = result.regeocode.formattedAddress
            
            currentLocation.value = {
              name: addressComponent.township || addressComponent.district || '当前位置',
              address: formattedAddress,
              district: `${addressComponent.district}${addressComponent.adname}`,
              location: `${lng},${lat}`,
              lng: lng,
              lat: lat,
              pname: addressComponent.province,
              cityname: addressComponent.city,
              adname: addressComponent.district
            }
            
            console.log('✅ 自动定位成功:', currentLocation.value)
            console.log('📍 当前位置:', formattedAddress)
          } else {
            console.warn('⚠️ 逆地理编码失败，但地图已定位到坐标位置')
            // 即使逆地理编码失败，也保存基本信息
            currentLocation.value = {
              name: '当前位置',
              address: `坐标: ${lng}, ${lat}`,
              location: `${lng},${lat}`,
              lng: lng,
              lat: lat
            }
            isLocating.value = false
          }
        })
      },
      (error) => {
        isLocating.value = false
        console.warn('⚠️ 浏览器定位失败，尝试使用高德地图定位插件:', error.message)
        
        // 定位失败时，尝试使用高德地图定位插件
        if (geolocation) {
          console.log('尝试使用高德地图定位插件...')
          geolocation.getCurrentPosition((status, result) => {
            if (status === 'complete') {
              const lng = result.position.lng
              const lat = result.position.lat
              
              currentLocation.value = {
                name: result.formattedAddress || '当前位置',
                address: result.formattedAddress,
                location: `${lng},${lat}`,
                lng: lng,
                lat: lat
              }
              
              if (map) {
                map.setCenter([lng, lat])
                map.setZoom(15)
                addMarkerToMap([lng, lat], '当前位置')
                console.log('✅ 高德地图定位成功:', currentLocation.value)
              } else {
                console.warn('地图尚未初始化，无法定位')
              }
            } else {
              console.error('❌ 高德地图定位也失败:', status)
              // 不弹窗提示，只在控制台输出，避免打扰用户
              console.warn('提示：定位失败，地图显示默认位置（北京）。您可以手动点击定位按钮重试，或搜索地点。')
            }
          })
        } else {
          console.warn('高德地图定位插件未初始化')
        }
      },
      {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 0
      }
    )
  } else {
    // 浏览器不支持定位，使用高德地图定位插件
    console.warn('浏览器不支持定位API，尝试使用高德地图定位插件')
    isLocating.value = false
    if (geolocation) {
      geolocation.getCurrentPosition((status, result) => {
        if (status === 'complete') {
          const lng = result.position.lng
          const lat = result.position.lat
          
          currentLocation.value = {
            name: result.formattedAddress || '当前位置',
            address: result.formattedAddress,
            location: `${lng},${lat}`,
            lng: lng,
            lat: lat
          }
          
          if (map) {
            map.setCenter([lng, lat])
            map.setZoom(15)
            addMarkerToMap([lng, lat], '当前位置')
          } else {
            console.warn('地图尚未初始化，无法定位')
          }
          
          console.log('✅ 高德地图定位成功:', currentLocation.value)
        } else {
          console.warn('高德地图定位失败:', status)
        }
      })
    } else {
      console.warn('高德地图定位插件未初始化')
    }
  }
}

// 在地图上添加标记
const addMarkerToMap = (position, title) => {
  if (!map) {
    console.warn('地图未初始化，无法添加标记')
    return
  }
  
  try {
    // 验证坐标有效性
    if (!position || !Array.isArray(position) || position.length < 2) {
      console.error('无效的坐标格式:', position)
      return
    }
    
    const lng = Number(position[0])
    const lat = Number(position[1])
    
    // 检查坐标是否为有效数字
    if (isNaN(lng) || isNaN(lat)) {
      console.error('坐标包含无效数字:', position, 'lng:', lng, 'lat:', lat)
      return
    }
    
    // 检查坐标范围（经度：-180 到 180，纬度：-90 到 90）
    if (lng < -180 || lng > 180 || lat < -90 || lat > 90) {
      console.error('坐标超出有效范围:', { lng, lat })
      return
    }
    
    const validPosition = [lng, lat]
    
    // 清除之前的标记
    if (currentMarker) {
      map.remove(currentMarker)
      currentMarker = null
    }
    
    console.log('正在添加标记到位置:', validPosition, '标题:', title)
    
    // 创建新标记
    currentMarker = new AMap.Marker({
      position: validPosition,
      title: title || '位置标记',
      icon: new AMap.Icon({
        size: new AMap.Size(32, 32),
        image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png'
      })
    })
    
    map.add(currentMarker)
    
    console.log('✅ 标记已添加到地图')
    
    // 确保地图中心点和缩放级别（如果还没有设置）
    const currentCenter = map.getCenter()
    if (currentCenter) {
      const distance = Math.sqrt(
        Math.pow(currentCenter.lng - validPosition[0], 2) + 
        Math.pow(currentCenter.lat - validPosition[1], 2)
      )
      
      // 如果距离较远，重新定位
      if (distance > 0.01 && map) {
        map.setCenter(validPosition)
        map.setZoom(15)
        console.log('地图已重新定位到标记位置')
      }
    }
  } catch (error) {
    console.error('添加标记失败:', error)
  }
}

// 清除地图上的所有标记
const clearMapMarkers = () => {
  if (!map) return
  
  if (markers.length > 0) {
    map.remove(markers)
    markers = []
  }
  if (currentMarker) {
    map.remove(currentMarker)
    currentMarker = null
  }
}

// 地点搜索
const searchLocation = () => {
  if (!locationSearchKeyword.value.trim()) {
    locationSearchResults.value = []
    return
  }
  
  // 防抖处理
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  
  searchTimeout = setTimeout(() => {
    performLocationSearch()
  }, 300)
}

// 执行地点搜索
const performLocationSearch = () => {
  if (!locationSearchKeyword.value.trim()) {
    return
  }
  
  // 如果搜索服务未初始化，先初始化
  if (!placeSearch) {
    initPlaceSearch()
    // 等待插件加载完成后再搜索
    setTimeout(() => {
      if (placeSearch) {
        doSearch()
      } else {
        locationSearching.value = false
        alert('地点搜索服务初始化失败，请刷新页面重试')
      }
    }, 500)
    return
  }
  
  doSearch()
}

// 实际执行搜索的函数
const doSearch = () => {
  if (!placeSearch || !locationSearchKeyword.value.trim()) {
    return
  }
  
  locationSearching.value = true
  locationSearchResults.value = []
  selectedLocationIndex.value = -1
  
  // 清除地图上的标记
  clearMapMarkers()
  
  placeSearch.search(locationSearchKeyword.value, (status, result) => {
    locationSearching.value = false
    
    if (status === 'complete' && result.poiList && result.poiList.pois) {
      locationSearchResults.value = result.poiList.pois.map(poi => ({
        name: poi.name,
        address: poi.address || poi.district + poi.adname,
        district: poi.district + poi.adname,
        location: poi.location ? `${poi.location.lng},${poi.location.lat}` : '',
        lng: poi.location ? poi.location.lng : null,
        lat: poi.location ? poi.location.lat : null,
        pname: poi.pname, // 省份
        cityname: poi.cityname, // 城市
        adname: poi.adname, // 区县
        tel: poi.tel || '',
        type: poi.type || ''
      }))
      
      // 在地图上标记所有搜索结果
      if (map && locationSearchResults.value.length > 0) {
        locationSearchResults.value.forEach((location, index) => {
          if (location.lng && location.lat) {
            const marker = new AMap.Marker({
              position: [location.lng, location.lat],
              title: location.name,
              icon: new AMap.Icon({
                size: new AMap.Size(28, 28),
                image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'
              })
            })
            
            // 点击标记时选择该地点
            marker.on('click', () => {
              selectLocationFromList(location, index)
            })
            
            map.add(marker)
            markers.push(marker)
          }
        })
        
        // 自动定位到第一个搜索结果
        if (locationSearchResults.value.length > 0 && map) {
          const firstResult = locationSearchResults.value[0]
          if (firstResult.lng && firstResult.lat) {
            // 定位到第一个搜索结果
            map.setCenter([firstResult.lng, firstResult.lat])
            map.setZoom(15)
            
            // 如果有多个结果，调整视野以包含所有标记
            if (markers.length > 1 && map) {
              setTimeout(() => {
                if (map) {
                  map.setFitView(markers, false, [50, 50, 50, 50])
                }
              }, 300)
            }
          }
        }
      }
    } else if (status === 'no_data') {
      locationSearchResults.value = []
    } else {
      console.error('地点搜索失败:', status)
      locationSearchResults.value = []
    }
  })
}

// 搜索框获得焦点
const onLocationSearchFocus = () => {
  // 确保地图已初始化
  if (!map) {
    return
  }
  
  // 如果搜索服务未初始化，则初始化
  if (!placeSearch) {
    initPlaceSearch()
  }
}

// 从列表选择地点
const selectLocationFromList = (location, index) => {
  selectedLocationIndex.value = index
  
  // 在地图上标记选中的地点
  if (location && location.lng != null && location.lat != null) {
    const lng = Number(location.lng)
    const lat = Number(location.lat)
    if (!isNaN(lng) && !isNaN(lat)) {
      addMarkerToMap([lng, lat], location.name)
    } else {
      console.warn('地点坐标无效:', location)
    }
  }
  
  // 选择地点
  selectLocation(location)
}

// 选择地点
const selectLocation = (location) => {
  if (typeof location === 'string') {
    // 兼容旧代码
    formData.value.location = location
    formData.value.locationData = { name: location }
  } else {
    // 新代码：保存完整地点信息
    formData.value.location = location.name
    formData.value.locationData = location
    
    // 如果有点位信息，在地图上标记
    if (location && location.lng != null && location.lat != null) {
      const lng = Number(location.lng)
      const lat = Number(location.lat)
      if (!isNaN(lng) && !isNaN(lat)) {
        addMarkerToMap([lng, lat], location.name)
      }
    } else if (location.location) {
      // 如果有location字符串（格式：lng,lat）
      const [lng, lat] = location.location.split(',').map(Number)
      if (!isNaN(lng) && !isNaN(lat)) {
        addMarkerToMap([lng, lat], location.name)
      }
    }
  }
  
  // 不关闭弹窗，让用户可以看到地图上的标记
  // showLocationModal.value = false
  // locationSearchKeyword.value = ''
  // locationSearchResults.value = []
}

// 关闭地点弹窗
const closeLocationModal = () => {
  showLocationModal.value = false
  locationSearchKeyword.value = ''
  locationSearchResults.value = []
  selectedLocationIndex.value = -1
  clearMapMarkers()
}

// 清除地点
const clearLocation = () => {
  formData.value.location = ''
  formData.value.locationData = null
  clearMapMarkers()
  closeLocationModal()
}

const saveDraft = () => {
  // 保存到localStorage
  const draft = {
    images: images.value,
    ...formData.value,
    createdAt: new Date().toISOString()
  }
  localStorage.setItem('draft_content', JSON.stringify(draft))
  alert('已保存到草稿箱')
  router.back()
}

const handlePublish = async () => {
  if (!canPublish.value) {
    alert('请至少填写标题或内容')
    return
  }

  try {
    // 如果有图片，先上传
    const mediaUrls = []
    for (const img of images.value) {
      // 这里应该上传到服务器
      // 暂时使用预览图作为示例
      mediaUrls.push(img.preview)
    }

    const token = localStorage.getItem('token')
    
    const response = await axios.post('/content/publish', {
      title: formData.value.title,
      content: formData.value.content,
      media_urls: mediaUrls,
      media_type: images.value.length > 0 ? 1 : 0,
      tags: formData.value.topics.join(','),
      location: formData.value.location,
      location_data: formData.value.locationData // 发送完整的地点信息
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.data.success) {
      alert('发布成功！')
      router.push('/feed')
    } else {
      alert('发布失败：' + response.data.message)
    }
  } catch (error) {
    console.error('发布失败:', error)
    alert('发布失败，请重试')
  }
}

const handleBack = () => {
  if (images.value.length > 0 || formData.value.title || formData.value.content) {
    if (confirm('确定要退出吗？未保存的内容将丢失')) {
      router.back()
    }
  } else {
    router.back()
  }
}

// 生命周期
onMounted(() => {
  // 等待高德地图SDK加载完成
  if (typeof AMap !== 'undefined') {
    // SDK已加载，但不立即初始化地图（等弹窗打开时再初始化）
  } else {
    // 如果SDK还未加载，等待一段时间后重试
    const checkAMap = setInterval(() => {
      if (typeof AMap !== 'undefined') {
        clearInterval(checkAMap)
      }
    }, 100)
    
    // 10秒后停止检查
    setTimeout(() => {
      clearInterval(checkAMap)
    }, 10000)
  }
  
  // 监听弹窗显示状态，初始化地图
  watch(showLocationModal, (newVal) => {
    if (newVal) {
      // 弹窗显示后，等待DOM更新再初始化地图
      nextTick(() => {
        setTimeout(() => {
          if (mapContainer.value) {
            if (!map) {
              // 首次初始化地图
              initMap()
            } else {
              // 如果地图已存在，刷新地图大小和显示
              try {
                map.getSize()
                // 强制刷新地图
                setTimeout(() => {
                  if (map) {
                    map.getSize()
                  }
                }, 200)
              } catch (error) {
                console.error('刷新地图大小失败:', error)
                // 如果刷新失败，重新初始化
                if (map) {
                  map.destroy()
                  map = null
                }
                initMap()
              }
            }
          }
        }, 300)
      })
    } else {
      // 弹窗关闭时，清除标记
      clearMapMarkers()
    }
  })
})

onBeforeUnmount(() => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  if (map) {
    map.destroy()
    map = null
  }
  placeSearch = null
  markers = []
  currentMarker = null
})
</script>

<style scoped>
.publish-container {
  width: 100vw;
  min-height: 100vh;
  background: white;
  padding-bottom: 80px;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 15px;
  background: #f5f5f5;
  font-size: 12px;
}

.status-icons {
  display: flex;
  gap: 5px;
}

/* 导航栏 */
.publish-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.back-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  padding: 5px 10px;
}

.nav-title {
  font-size: 16px;
  font-weight: bold;
}

/* 上传区域 */
.upload-section {
  padding: 15px;
}

.upload-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.upload-item {
  aspect-ratio: 1;
  border-radius: 10px;
  overflow: hidden;
  position: relative;
  background: #f5f5f5;
}

.upload-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-item.add-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px dashed #ddd;
  cursor: pointer;
}

.plus-icon {
  font-size: 40px;
  color: #999;
}

.remove-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 24px;
  height: 24px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 18px;
}

/* 输入区域 */
.input-section {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.title-input {
  width: 100%;
  border: none;
  outline: none;
  font-size: 16px;
  padding: 10px 0;
}

.content-input {
  width: 100%;
  border: none;
  outline: none;
  font-size: 14px;
  padding: 10px 0;
  resize: none;
}

/* 标签区域 */
.tag-section {
  padding: 15px;
  display: flex;
  gap: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.tag-btn {
  padding: 8px 16px;
  background: #f5f5f5;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
}

.tag-btn:hover {
  background: #e0e0e0;
}

/* 地点区域 */
.location-section {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.location-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.location-icon {
  font-size: 16px;
}

.location-text {
  font-size: 14px;
  color: #666;
}

/* 弹窗 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
}

.modal-content {
  background: white;
  width: 100%;
  max-height: 60vh;
  border-radius: 20px 20px 0 0;
  padding: 20px;
  overflow-y: auto;
}

.modal-content h3 {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}

.search-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 10px;
  margin-bottom: 15px;
  outline: none;
}

.tag-list, .location-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.tag-option {
  padding: 8px 16px;
  background: #f5f5f5;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.tag-option.active {
  background: #007AFF;
  color: white;
}

.location-option {
  width: 100%;
  padding: 12px;
  background: #f5f5f5;
  border-radius: 10px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 10px;
}

.loc-icon {
  font-size: 18px;
}

/* 地点搜索弹窗样式 */
.location-modal {
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

/* 地图容器 */
.map-container {
  width: 100%;
  min-height: 300px;
  height: 300px;
  margin-bottom: 15px;
  border-radius: 10px;
  overflow: hidden;
  border: 1px solid #ddd;
  background: #f5f5f5;
  position: relative;
}

.map-container::before {
  content: '地图加载中...';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #999;
  font-size: 14px;
  z-index: 1;
}

.map-container.amap-container {
  z-index: 2;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 28px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
}

.location-search {
  position: relative;
  margin-bottom: 15px;
  display: flex;
  gap: 8px;
  align-items: center;
}

.location-search-input {
  flex: 1;
  padding: 12px 40px 12px 15px;
  border: 1px solid #ddd;
  border-radius: 10px;
  font-size: 14px;
  outline: none;
}

.location-search-input:focus {
  border-color: #007AFF;
}

.search-icon {
  position: absolute;
  right: 50px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 18px;
  pointer-events: none;
}

.location-btn {
  width: 40px;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  transition: all 0.2s;
  flex-shrink: 0;
}

.location-btn:hover {
  background: #f5f5f5;
  border-color: #007AFF;
}

.location-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}

.location-results {
  max-height: 250px;
  overflow-y: auto;
  margin-bottom: 15px;
}

.result-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  font-weight: 500;
}

.location-result-item {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  display: flex;
  align-items: flex-start;
  gap: 10px;
  transition: background 0.2s;
}

.location-result-item:hover {
  background: #f5f5f5;
}

.location-result-item.active {
  background: #e3f2fd;
  border-left: 3px solid #007AFF;
}

.location-result-item:last-child {
  border-bottom: none;
}

.location-info {
  flex: 1;
}

.location-name {
  font-size: 15px;
  color: #333;
  margin-bottom: 4px;
  font-weight: 500;
}

.location-address {
  font-size: 12px;
  color: #999;
}

.no-results {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  font-size: 14px;
}

.location-tips {
  margin-bottom: 15px;
}

.tip-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  font-weight: 500;
}

.clear-location-btn {
  width: 100%;
  padding: 10px;
  background: #f5f5f5;
  color: #666;
  border: none;
  border-radius: 10px;
  font-size: 14px;
  cursor: pointer;
  margin-top: 10px;
}

.clear-location-btn:hover {
  background: #e0e0e0;
}

.user-list {
  max-height: 200px;
  overflow-y: auto;
  margin-bottom: 20px;
}

.user-item {
  padding: 12px;
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  border-radius: 10px;
}

.user-item:hover {
  background: #f5f5f5;
}

.user-avatar {
  width: 40px;
  height: 40px;
  background: #e0e0e0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-confirm {
  width: 100%;
  padding: 12px;
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  cursor: pointer;
}

/* 底部操作栏 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 10px 15px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
}

.draft-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 10px 15px;
  cursor: pointer;
}

.draft-icon {
  font-size: 20px;
}

.draft-text {
  font-size: 12px;
  color: #666;
}

.publish-btn {
  flex: 1;
  padding: 12px;
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
}

.publish-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>

